package com.enjoy.nettyhttp.server;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

/**
 * Created by HP on 2019/7/15.
 */
public class BusiHandler extends ChannelInboundHandlerAdapter {
    private void  send(ChannelHandlerContext ctx, String context, HttpResponseStatus status){
        FullHttpResponse response =new DefaultFullHttpResponse(
                HttpVersion.HTTP_1_1,status, Unpooled.copiedBuffer(context, CharsetUtil.UTF_8));
        response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain;charset=UTF-8");
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String result="";
        FullHttpRequest httpRequest= (FullHttpRequest) msg;
        System.out.println(httpRequest.headers());

        try {
            String path=httpRequest.uri();
            String body=httpRequest.content().toString(CharsetUtil.UTF_8);
            HttpMethod method=httpRequest.method();

            if (!"/test".equalsIgnoreCase(path)){
                result="非法请求"+path;
                send(ctx,result,HttpResponseStatus.BAD_REQUEST);
                return;
            }

            System.out.println("接受到："+method);
            if (HttpMethod.GET.equals(method)){
                System.out.println("body:"+body);
                result="GET请求，应答："+"鸡你太美";
                send(ctx,result,HttpResponseStatus.OK);
                return;
            }
            //如果是其他类型请求，如post
            if(HttpMethod.POST.equals(method)){
                //接受到的消息，做业务逻辑处理...
                //....
                return;
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            httpRequest.release();
        }
    }
}
